﻿using FFIV.Lib.BusinessRules;
using FFIV.Lib.DataComponent;
using FFIV.Lib.Model;

namespace FFIV.Lib.Utilities
{
	public class CategoriesUtility
	{
		/// <summary>
		/// 类别树缓存是否有效
		/// </summary>
		public static bool IsCategoryCacheAble { get; set; }

		/// <summary>
		/// 类别树缓存
		/// </summary>
		public static CategoryNode CategoryCache { get; set; }

		static CategoriesUtility()
		{
			IsCategoryCacheAble = false;
		}

		/// <summary>
		/// 获取所有类别的类别树
		/// </summary>
		public static CategoryNode GetCategories()
		{
			// 判断缓存是否有效，无效则构建类别树缓存
			if (!IsCategoryCacheAble || CategoryCache == null)
			{
				CategoryCache = BuildCategoriesTree();
				IsCategoryCacheAble = true;
			}
			return CategoryCache;
		}

		public static void DisableCache()
		{
			IsCategoryCacheAble = false;
		}

		public static CategoryNode GetCategoryNodeById(int categoryId)
		{
			CategoryNode result = SearchCategoryNode(CategoryCache, categoryId);
			return result ?? new CategoryNode();
		}

		private static CategoryNode SearchCategoryNode(CategoryNode parentNode, int categoryId)
		{
			if (parentNode.Id == categoryId)
			{
				return parentNode;
			}

			foreach (CategoryNode item in parentNode.Children)
			{
				CategoryNode result = SearchCategoryNode(item, categoryId);
				if (result != null)
				{
					return result;
				}
			}

			return null;
		}

		private static CategoryNode BuildCategoriesTree()
		{
			// 类别树根节点
			CategoryNode result = new CategoryNode { Id = 0, Depth = 0 };

			CategoryDS.CategoriesDataTable table = CategoriesRules.GetAllCategories();
			BuildCateoriyNode(table, result);

			return result;
		}

		private static void BuildCateoriyNode(CategoryDS.CategoriesDataTable table, CategoryNode parentNode)
		{
			// 查找所有结点中属于当前节点的子结点，深度优先创建类别树
			foreach (CategoryDS.CategoriesRow row in table)
			{
				if (row.ParentId == parentNode.Id)
				{
					CategoryNode node = new CategoryNode
										{
											Id = row.CategoryId,
											Name = row.Name,
											ArticleCount = row.ArticleCount,
											Parent = parentNode,
											Depth = parentNode.Depth + 1
										};
					parentNode.Children.Add(node);

					BuildCateoriyNode(table, node);
				}
			}
		}
	}
}
